package com.the_ring.chapter11.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.the_ring.chapter11.bean.PathPosition;

import java.util.ArrayList;
import java.util.List;

public class SignatureView extends View {

    private Paint mPathPaint = new Paint();                     // 声明一个画笔对象
    private Path mPath = new Path();                            // 声明一个路径对象
    private int mPathPaintColor = Color.BLACK;                  // 画笔颜色
    private int mStrokeWidth = 3;                               // 画笔线宽
    private PathPosition mPathPos = new PathPosition();         // 路径位置
    private List<PathPosition> mPathList = new ArrayList<>();   // 路径位置列表
    private PointF mLastPos;                                    // 上次触摸点的横、纵坐标

    public SignatureView(Context context) {
        this(context, null);
    }

    public SignatureView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    // 初始化视图
    private void initView() {
        mPathPaint.setStrokeWidth(mStrokeWidth);    // 设置画笔的线宽
        mPathPaint.setStyle(Paint.Style.STROKE);    // 设置画笔的类型，STROKE 表示空心
        mPathPaint.setColor(mPathPaintColor);       // 设置画笔颜色
        setDrawingCacheEnabled(true);               // 开启当前视图的绘图缓存
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawPath(mPath, mPathPaint);         // 在画笔上绘制指定路径线条
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                mPathPos.prePos = new PointF(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                mPath.quadTo(mLastPos.x, mLastPos.y, event.getX(), event.getY());
                mPathPos.nextPos = new PointF(event.getX(), event.getY());
                mPathList.add(mPathPos);
                mPathPos = new PathPosition();
                mPathPos.prePos = new PointF(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_UP:
                mPath.quadTo(mLastPos.x, mLastPos.y, event.getX(), event.getY());
                break;
        }
        mLastPos = new PointF(event.getX(), event.getY());
        postInvalidate();
        return true;
    }
}
